import UIKit

extension UIView {

    var snapshot: UIImage {
        UIGraphicsImageRenderer(bounds: bounds).image { rendererContext in
            layer.render(in: rendererContext.cgContext)
        }
    }
    
    func snapshot(of rect: CGRect) -> UIImage {
        UIGraphicsImageRenderer(bounds: rect).image { rendererContext in
            layer.render(in: rendererContext.cgContext)
        }
    }
}
extension CGRect {    
    func scaleToFill(in rect: CGRect) -> CGRect {
        let ratio = self.width/self.height
        let targetRatio = rect.width/rect.height
        
        if (targetRatio > ratio) {
            /// target rect's width has more space than height
            let h = rect.height
            let w = h * ratio
            return CGRect(x: rect.minX + (rect.width - w) * 0.5, y: rect.minY, width: w, height: h)
        } else {
            /// target rect's height has more space than width
            let w = rect.width
            let h = w / ratio
            return CGRect(x: rect.minX, y: rect.minY + (rect.height - h) * 0.5, width: w, height: h)
        }
    }
}
